package com.my.algorithmlearning.leetcode.slidewindow;

import org.springframework.util.Assert;

/**
 * @ClassName Medium_209_MinimumSizeSubarraySum
 * @Description 题目：https://leetcode.cn/problems/minimum-size-subarray-sum/?envType=study-plan-v2&envId=top-interview-150
 * @Author wanghaiwei
 * @Date 2024-04-19
 */
public class Medium_209_MinimumSizeSubarraySum {
    public int minSubArrayLen(int target, int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int i = 0;
        int j = 0;
        int minLength = 0;
        int sum = 0;
        while(i < nums.length) {
            if (sum >= target) {
                if (minLength == 0) {
                    minLength = j - i;
                }else {
                    minLength = Math.min(j - i, minLength);
                }
                if (minLength == 1) {
                    return minLength;
                }
                //滑动窗口
                sum -= nums[i];
                i++;
            }else if(j < nums.length){
                sum += nums[j];
                j++;
            }else if(j >= nums.length) {
                sum -= nums[i];
                i++;
            }
        }
        return minLength;
    }

    public static void main(String[] args) {
        Medium_209_MinimumSizeSubarraySum solution = new Medium_209_MinimumSizeSubarraySum();
        Assert.isTrue(solution.minSubArrayLen(7, new int[]{2,3,1,2,4,3}) == 2
                , "target=7,{2,3,1,2,4,3}解答错误" );
    }
}
